#!/bin/bash

export LANG=C

#######################################################################################
# 1. Working directory configuration
#######################################################################################
SHELL_DIR=$(cd $(dirname "${BASH_SOURCE[0]}") && pwd )

# 2.check gcc
[ -z "$CROSS_COMPILE" ] && CROSS_COMPILE=/opt/aarch64-linux-gnu-gcc-x86_64-6.3.1-2017/bin/aarch64-linux-gnu-
[ -z "$APLAY_INSTALL_DIR" ] && APLAY_INSTALL_DIR=${SHELL_DIR}/out

if [ -z "$THREAD2" ]; then
    MAX_THREAD=`grep 'processor' /proc/cpuinfo | sort -u | wc -l`
    _THREAD=`expr $MAX_THREAD \* 2`
    export THREAD2="-j${_THREAD}"
fi

function build_lib()
{
    cd ${SHELL_DIR}/alsa-lib
    git checkout libtool 
    autoreconf -ivf # SOLVE [ WARNING: 'aclocal-1.14' is missing on your system. ]
    # --enable-static=yes --enable-shared=no
    CC=${CROSS_COMPILE}gcc ./configure --host=arm-linux  --prefix=${APLAY_INSTALL_DIR}
    make ${THREAD2}
    make ${THREAD2} install
    make distclean
}


function build_utils()
{
    cd ${SHELL_DIR}/alsa-utils
    export DESTDIR=${APLAY_INSTALL_DIR}/utils
    CC=${CROSS_COMPILE}gcc ./configure --host=arm-linux  \
    --with-alsa-inc-prefix=${APLAY_INSTALL_DIR}/include --with-alsa-prefix=${APLAY_INSTALL_DIR}/lib \
    --disable-alsamixer --disable-xmlto --disable-nls

    # SOLVE [ WARNING: 'aclocal-1.14' is missing on your system. ]
    autoreconf -ivf 
    touch configure.ac aclocal.m4 configure Makefile.am Makefile.in
    
    make ${THREAD2}
    rm -rf ${APLAY_INSTALL_DIR}/utils
    make ${THREAD2} install
    make distclean
}

# build aplay
build_lib && build_utils
